import datetime, time

import requests

from manager.app.worker.workerController import RobotServiceWorker
from manager.app.robot.model import Project, RobotInstance
from manager.app.util.http import request


class DouyinWorker(RobotServiceWorker):
    def __init__(self, server):
        super().__init__(server)

    def _worker_url(self):
        return self.server

    def get_daemon_status(self):
        pass


    def start_robot(self, project_name, robot_name, arguments):
        post_data = dict(project=project_name, robot=robot_name)
        post_data.update(arguments)
        data = request("post", self._worker_url() + "/schedule.json", data=post_data, return_type="json")
        return data['jobid'] if data and data['status'] == 'ok' else None

    def cancel_robot(self, project_name, job_id):
        post_data = dict(project=project_name, job=job_id)
        data = request("post", self._worker_url() + "/cancel.json", data=post_data, return_type="json")
        return data != None

    def deploy(self, project_name, file_path):
        with open(file_path, 'rb') as f:
            eggdata = f.read()
        res = requests.post(self._worker_url() + '/addversion.json', data={
            'project': project_name,
            'version': int(time.time()),
            'egg': eggdata,
        })
        return res.text if res.status_code == 200 else None

    def log_url(self, project_name, robot_name, job_id):
        return self._worker_url() + '/logs/%s/%s/%s.log' % (project_name, robot_name, job_id)
